<template>
  <DetailsFormBox :title="dataInfo?.table?.title" leftWidth="35%" :type="route.query.type" :form="data.form" :btns="[
    {
      title: `${data.form?.baseData?.isLocked === 0 ? '审核' : '反审核'}彩稿`,
      icon: '',
      type: 'primary',
      click: (form: any) => {
        if (form?.baseData?.isLocked === 0) {
          setState(1, '审核成功')
        } else {
          setState(0, '反审核成功')
        }
      },
    },
    {
      title: `${data.form?.baseData?.isLockedProduct === 0 ? '锁定' : '解锁'}产品`,
      icon: '',
      type: 'primary',
      click: (form: any) => {
        if (form?.baseData?.isLockedProduct === 0) {
          setState(9, '锁定成功')
        } else {
          setState(8, '解锁成功')
        }

      },
    },
  ]" :loading="data.loading" :json="dataInfo">
    <template #left="{ form }">
      <ProductBox :form="form" :options="options" />
    </template>
    <template #headR="{ form }">
      <div class="flex-w list-r-8">
        <div>
          <span>锁定状态：</span>
          <ElTagBox :data="form.baseData?.isLockedProduct" :options="options.productState" />
        </div>
        <el-divider direction="vertical" />
        <div>
          <span>彩稿状态：</span>
          <ElTagBox :data="form.baseData?.isLocked" :options="options.processState" />
        </div>
        <el-divider direction="vertical" />
        <div>
          <span>业务信息：</span>
          <ElTagBox :data="form.baseData?.isCompletedBusniess" :options="options.writeState" />
        </div>
        <el-divider direction="vertical" />
        <div>
          <span>设计信息：</span>
          <ElTagBox :data="form.baseData?.isCompletedDesign" :options="options.writeState" />
        </div>
        <el-divider direction="vertical" />
        <div>
          <span>生产信息：</span>
          <ElTagBox :data="form.baseData?.isCompletedProduce" :options="options.writeState" />
        </div>
        <el-divider direction="vertical" />
        <div>
          <span>包装信息：</span>
          <ElTagBox :data="form.baseData?.isCompletedPackage" :options="options.writeState" />
        </div>
      </div>
    </template>
    <template #default="{ form }">
      <div class="customerBox m-8">
        <div class="header list-b-8 p-12">
          <div class="flex-start-center list-r-8">
            <h1>{{ form.baseData?.productName || '--' }}</h1>
            <ElTagBox :data="form.baseData?.productLayout" :options="proxy.$optionsArr.productLayout">
              {{ `${form.baseData?.productLayout} V${Number(form.baseData?.newVersion) +
                Number(form.baseData?.updateVersion)}`
              }}
            </ElTagBox>
          </div>
          <div class="flex-w list-r-8">
            <span>产品编号：{{ form.baseData?.productNumber || '--' }}</span>
            <el-divider direction="vertical" />
            <span>客户名称：{{ form.baseData?.customerName || '--' }}</span>
          </div>
        </div>
        <ElTabsBox active="" :data="[
          {
            label: '业务信息',
            value: 'tabs1',
            template: 'BusinessInformation',
          },
          {
            label: '标签信息',
            value: 'tabs2',
            template: 'TagInformation',
          },
          {
            label: '产品型号',
            value: 'tabs3',
            template: 'FinishedProductModel',
          },
          {
            label: '彩稿信息',
            value: 'tabs4',
            template: 'ColorManuscriptInformation',
          },
          {
            label: '生产信息',
            value: 'tabs5',
            template: 'ProductionInformation',
          },
          {
            label: '包装信息',
            value: 'tabs6',
            template: 'PackageInformation',
          },
          {
            label: '工艺资料卡',
            value: 'tabs7',
            template: 'ProcessDataCard',
          },
          {
            label: '授权委托书',
            value: 'tabs8',
            template: 'LetterOfAuthorization',
          },
        ]" :query="{
          data: form,//主表信息
          relatedCode: form.baseData.productCode,//是否编辑
          options: options,//是否编辑
          isEdit: isEdit,//是否编辑
          setState: setState,//保存方法
        }" :templateObj="{
          BusinessInformation,
          ProductionInformation,
          PackageInformation,
          ColorManuscriptInformation,
          TagInformation,
          ProcessDataCard,
          FinishedProductModel,
          LetterOfAuthorization,
        }" @saveBtn="getForm" />
      </div>
    </template>
  </DetailsFormBox>
</template>
<script setup lang="ts">
import { sendMsg } from '@/utils/crossTagMag.ts';
import { getProductType } from '@/utils/optionsArr.ts';
import { getCurrentInstance, onMounted, reactive } from 'vue';
import { useRoute } from 'vue-router';
import { useListComponent } from '../pageTs'; // 引入逻辑
import BusinessInformation from './BusinessInformation.vue'; // 业务信息
import ColorManuscriptInformation from './ColorManuscriptInformation.vue'; // 彩稿信息
import FinishedProductModel from './FinishedProductModel.vue'; // 成品型号
import LetterOfAuthorization from './LetterOfAuthorization.vue'; // 授权委托书
import PackageInformation from './PackageInformation.vue'; // 包装信息
import ProcessDataCard from './ProcessDataCard.vue'; // 工艺资料卡
import ProductBox from './ProductBox.vue'; // 业务信息
import ProductionInformation from './ProductionInformation.vue'; // 生产信息
import TagInformation from './TagInformation.vue'; // 标签信息
const { dataInfo, options } = useListComponent();
const { proxy } = getCurrentInstance() as any;
const data: any = reactive({
  loading: false,
  loadingMsg: '',
  form: {
    originalQuantity: null, // 原库存数 = 库存总数量 - 客户待发货数量
    baseData: {
      productID: 0, // 产品主键ID
      productCode: "", // 产品编码（唯一识别码）
      productNumber: "", // 产品编号（客户编号+流水号，展示字段）
      baseProductCode: "", // 产品模板基础编号（新版改版共用）
      productName: "", // 产品名称
      customerCode: "", // 客户编码（唯一识别码）
      productSource: 0, // 产品来源：0新系统；1老系统
      productLayout: "", // 产品版面
      newVersion: 0, // 新版递增值
      updateVersion: 0, // 改版递增值
      productPrice: null, // 产品单价
      productRequirement: "", // 产品要求
      productType: "", // 产品类型（关联字典表）
      productPicture: "", // 产品图片
      productRemark: "", // 产品备注说明
      specialRemark: "", // 特殊备注
      specificationIndex: 0, // 型号流水号
      isLocked: 0, // 是否锁定彩稿
      isLockedProduct: 0, // 是否锁定产品
      minimumAmount: null, // 最低金额
      isCompletedBusniess: 0, // 是否完成业务信息
      isCompletedDesign: 0, // 是否完成设计信息
      isCompletedProduce: 0, // 是否完成生产信息
      isCompletedPackage: 0, // 是否完成包装信息
      createBy: "", // 创建人员（上传人员）
      createDate: "", // 创建时间（上传时间）
      modifyBy: "", // 修改人员
      modifyDate: "", // 修改时间
      isDisabled: 0, // 是否禁用：0否；1是
      isDeleted: 0, // 是否删除：0否；1是
      productStyle: 1, // 产品样式：1平张、2卷式、3折页
      productUnit: "", // 产品单位
      outDirection: 1, // 出标方向：1上、2下、3左、4右【卷式和折页有该属性】
      scrollDirection: 1, // 卷向：1页面朝内、2页面朝外【卷式有该属性】
      tagAffixWay: 1, // 贴标方式：1自动贴、2手帖
      mandrelSize: null, // 卷芯大小，单位：毫米【卷式有该属性】
      notOverDiameter: null, // 外直径不超过，单位：毫米【卷式有该属性】
      calculationMethod: 0, // 包装信息-计算方式
      pageEqualTags: null, // 每张等于X枚数/每卷等于X枚数
      packageEqualPages: null, // 每包等于X张数【平张和折页有该属性】
      eachBoxQuantity: 0, // 每箱数量
      cartonWeight: null, // 每个纸箱重量
      eachBoxWeight: null, // 每箱重量
      eachWeight: null, // 每个（套）标签重量
      cartonConfigCode: "", // 纸箱规格Code
      productionMode: 1, // 生产方式：0未选择；1版辊尺寸；2数码版面
      productionDimensions: null, // 生产尺寸
      makeupSpaceBetween: "", // 间距
      makeupSkipDistance: "", // 跳距
      marginSize: null, // 留边尺寸
      makeupPrintingCombine: "", // 印刷拼板
      makeupModules: "", // 刀模模数
      makeupPzDz: "", // 平张断张
      makeupColors: "", // 色数
      eachGroupQuantity: 0, // 每组标签数
      eachGroupHeight: null, // 每组高度
      knifeTimes: 0, // 每组刀数
      metersPerRoll: null, // 每卷米数
      knifeVersionCode: "", // 刀版编码
      plateInformation: "", // 印版信息
      productionRequirement: "", // 生产要求
      productTagNumber: 0, // 标签数量（冗余字段）
      productSize: "", // 产品尺寸（冗余字段）
      productTypeName: "", // 产品类型名称
      customerName: "", // 客户名称

      // 成品型号信息数组
      productSpecificationList: [
        {
          productSpecificationID: 0,
          productSpecificationCode: "",
          productCode: "",
          productSpecificationNumber: "",
          productSpecificationName: "",
          isDisable: 0,
          remark: "",
          stockQuantity: 0
        }
      ],

      // 阶梯价格信息数组
      productSteppedPriceInfoList: [
        {
          productSteppedPriceID: 0,
          productSteppedPriceCode: "",
          productCode: "",
          productSteppedCount: 0,
          productSteppedPrice: null,
          discount: null,
          remark: ""
        }
      ],

      // 标签信息数组
      productTagList: [
        {
          productTagID: 0,
          productTagCode: "",
          tagClientCode: "",
          productCode: "",
          productTagName: "",
          matchQuantity: 0,
          comparisonObject: "",
          percentageValue: 0,
          productTagPrice: null,
          tagShape: "",
          tagWidth: null,
          tagHeight: null,
          tagBorderRadius: null,
          tagBorder: null,
          tagType: 0,
          postedContent: "",
          surfaceRequires: "",
          scrapingCoatingColor: "",
          scrapingWordColor: "",
          scrapingCoatingColorName: "",
          scrapingWordColorName: ""
        }
      ],

      // 印刷层信息数组
      productTagPrintingLayerList: [
        {
          productPrintingLayerID: 0,
          productPrintingLayerCode: "",
          productLayerClientCode: "",
          productTagCode: "",
          isSurfaceLayer: 0,
          printingLayerName: "",
          printingMaterial: "",
          baseFilmColor: "",
          isHaveTechno: 0,
          technoPlaces: 0,
          technoColor: 0,
          isHaveBarCode: 0,
          barCodePlaces: 0,
          isLiuJiao: 0,
          liuJiaoTexture: "",
          printingMaterialName: "",
          baseFilmColorName: "",
          liuJiaoTextureName: ""
        }
      ],

      // 彩稿文件信息数组
      productColorDraftFileList: [
        {
          productColorDraftFileID: 0,
          productColorDraftCode: "",
          productCode: "",
          draftFileName: "",
          draftFileType: "",
          draftFileSize: null,
          draftFileUrl: "",
          draftFilePreview: "",
          uploadPerson: "",
          uploadTime: "",
          colorDraftType: 0,
          productTagCode: "",
          draftFileState: 0
        }
      ],

      // 颜色信息数组
      productPrintingColorList: [
        {
          productPrintingColorID: 0,
          productPrintingColorCode: "",
          productCode: "",
          colorCode: "",
          colorReference: 0,
          colorRemark: "",
          colorName: "",
          colorType: 0
        }
      ],

      // 材料信息数组
      productMaterialList: [
        {
          productMaterialID: 0,
          productMaterialCode: "",
          productCode: "",
          stockGoodsCode: "",
          materialName: "",
          specification: "",
          materialType: "",
          useType: 0,
          materialRemark: "",
          stockGoodsName: "",
          stockQuantity: 0,
          supplierCode: "",
          supplierName: "",
          materialNameInView: "",
          goodsUnitName: ""
        }
      ],

      // 工艺信息数组
      productTechniqueList: [
        {
          productTechniqueID: 0,
          productTechniqueCode: "",
          productCode: "",
          craftCode: "",
          deviceCode: "",
          craftRequirement: "",
          productTechniqueCardState: 0
        }
      ],

      // 设备集合
      produceMachineList: [
        {
          machineID: 0,
          machineCode: "",
          machineType: "",
          machineName: "",
          ownDepartment: 0,
          machineSort: 0,
          machinePictures: "",
          machineRemark: "",
          machineState: 0,
          isDelete: 0,
          createBy: "",
          createTime: "",
          modifyBy: "",
          modifyTime: ""
        }
      ],
      // 装箱信息数组
      productPackingInfoList: [
        {
          productPackingID: 0,
          productPackingCode: "",
          productCode: "",
          cartonCode: "",
          boxEqualPackages: 0,
          boxEqualTags: 0,
          describe: "",
          remark: "",
          cartonWeight: null
        }
      ]
    }
  },
});
// 获取当前路由对象
const route = useRoute();
const isEdit = computed(() => {
  let _query: any = route.query
  let _form: any = data.form
  return (_query.type === '2' && proxy.$permission('MenuCode1-6-3') && _form.baseData?.isLockedProduct === 0)
})
//单据状态
const setState = (state: number = 0, message: string = '保存成功') => {
  if (!!data.form?.baseData?.productCode) {
    proxy.$api.OrderBusniess.UpdateProductState({
      state: state, //	锁定状态筛选：0：解锁产品彩稿；1：锁定产品彩稿；2：完成业务信息；3：完成设计信息；4：完成生产信息；5：完成包装信息；6：禁用产品；7：启用产品；8：解锁产品；9：锁定产品；
      productCode: data.form.baseData.productCode,
    })
      .then((res: any) => {
        saveBtn(message)
      })
      .catch(() => { });
  }

};
const saveBtn = (message: string = '保存成功') => {
  proxy.$message(message)
  sendMsg('save', true);
  getForm()
  // window.close();
};
const getForm = () => {
  const _query = route.query
  if (_query.productCode) {
    data.loading = true
    proxy.$api.OrderBusniess.GetSingleProductByProductCode({
      queryBy: 2,
      queryValue: route.query.productCode
    })
      .then((res: any) => {
        const _productTagList: any[] = res.productTagList
        const _productTagListNew: any[] = [
          {
            productTagID: 0, // 订单产品标签主键ID
            productTagCode: "", // 订单产品标签代码（唯一识别码）
            tagClientCode: "", // 标签前端唯一识别码
            productCode: "", // 产品编码（唯一识别码）
            productTagName: "小标", // 订单产品标签名称
            matchQuantity: 0, // 配套数量
            comparisonObject: "", // 比例对象（比对标签）
            percentageValue: 0, // 比例值（包装比例）
            productTagPrice: 0.0, // 标签单价
            tagShape: "", // 标签形状：1长方形、2正方形、3圆形、4椭圆形、5异形
            tagWidth: 0.0, // 宽度/长度/直径，单位：毫米
            tagHeight: 0.0, // 高度/长度/直径，单位：毫米
            tagBorderRadius: 0.0, // R角，单位：毫米
            tagBorder: 0.0, // 边空，单位：毫米
            tagType: 1, // 标签类型：1 刮开；2 揭开；3 刮开+揭开；4 印刷；5 空白标
            postedContent: "", // 被贴物
            surfaceRequires: "", // 表面要求，多个用逗号隔开
            scrapingCoatingColor: "", // 刮开涂层颜色
            scrapingWordColor: "", // 刮开文字颜色
            scrapingCoatingColorName: "", // 刮开图层颜色
            scrapingWordColorName: "", // 刮开文字颜色
            productTagPrintingLayerList: [
              {
                productPrintingLayerID: 0, // 产品标签印刷主键ID
                productPrintingLayerCode: "", // 产品标签印刷代码（唯一识别码）
                productLayerClientCode: "", // 标签印刷层前端唯一识别码
                productTagCode: "", // 产品标签代码（唯一识别码）
                isSurfaceLayer: 1, // 是否为表层：1是；0否
                printingLayerName: "", // 印刷层名称
                printingMaterial: "", // 印刷材料
                baseFilmColor: "", // 层膜颜色
                isHaveTechno: 0, // 是否有数码：0否；1是
                technoPlaces: 0, // 数码位数
                technoColor: -1, // 数码颜色,-1:未选择、0：黑码、1：彩码
                isHaveBarCode: 0, // 是否有条码：0否；1是
                barCodePlaces: 0, // 条码位数
                isLiuJiao: 1, // 是否留胶：1是；0否
                liuJiaoTexture: "", // 留胶材质
                printingMaterialName: "", // 材料名称
                baseFilmColorName: "", // 底膜颜色名称
                liuJiaoTextureName: "" // 留胶材质
              }
            ]
          }
        ]
        data.form = {
          ...res,
          baseData: {
            ...res.baseData,
            productionMode: res.baseData.productionMode || 1,
          },
          productTagList: _productTagList.length > 0 ? _productTagList : _productTagListNew,
        }
        data.loading = false
      })
      .catch(() => { });
  }
};
//获取pinia
const keyName = `product-${route.query.productCode}`;
const handleBeforeUnload = () => {
  localStorage.removeItem(keyName);
}
onMounted(() => {
  getForm()
  getProductType(options, 'productType', (row: any) => {
    data.form.productType = row.objectCode
  }) //获取
  window.addEventListener('beforeunload', handleBeforeUnload);

});

onUnmounted(() => {

});
</script>
